from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
from bs4 import BeautifulSoup
import re
#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def getId(type,dd):

    #类型对应的详情id，后面继续完善
    typeCorrId = {
        "perio" : "article_id"
    }

    return dd[typeCorrId[type]]

def formData(response):
    allData = []
    soup = BeautifulSoup(response.text, "html5lib")

    allNum = soup.select(".BatchOper_result_show > span")[0].text
    px = re.compile("([0-9]+)")
    allNum = px.findall(allNum)[0]

    lis = soup.select(".ResultList")

    for li in lis:
        tempData = resultData()
        try:
            tempData["titleName"] = li.select(".title > a")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = "http://www.wanfangdata.com.cn" + li.select(".title > a")[0]["href"]
        except:
            pass

        try:
            tempData["author"] = [d.text for d in li.select(".author > a")]
        except:
            pass

        try:
            tempData["source"] = li.select(".Source > a")[0].text
        except:
            pass

        try:
            tempData["publishTime"] = li.select(".Volume > a")[0].text
        except:
            pass

        try:
            tempData["abstract"] = li.select(".summary")[0].text.strip()
        except:
            pass

        try:
            tempData["keyword"] = [d.text for d in li.select(".Keyword > a")]
        except:
            pass

        allData.append(tempData)

    return allData

def buildingParameters(data):
    # 主题、题名或关键词、题名、第一作者、作者单位、作者、关键词、摘要、基金、DOI
    # 主题:()*作者:()
    typeCorr = {
        "SU": "主题",
        "TI": "题名",
        "AU": "作者",
        "AF": "作者单位",
        "AB": "摘要",
        "KY": "关键词",
    }
    logCorr = {
        "and": "*",
        "or": "+",
        "not": "^",
        "###":"###"
    }

    data["log"].append("###")

    tempStr = []
    for i in range(len(data["values"])):

        try:
            strr = typeCorr[data["type"][i]] + ":" + "(" + data["values"][i] + ")" + "{}".format(logCorr[data["log"][i]])
            tempStr.append(strr)
        except:
            continue

    strr = ''
    for value in tempStr:
        strr += value

    return strr.strip().strip("#").strip()


def getData(keyword):

    headers = {
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://www.wanfangdata.com.cn/index.html',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('searchType', 'perio'),
        ('showType', ''),
        ('pageSize', ''),
        ('searchWord', keyword),
        ('isTriggerTag', ''),
    )

    response = requests.get('http://www.wanfangdata.com.cn/search/searchList.do', headers=headers, params=params,)

    result = formData(response)

    return result

def index(request):
    data = json.loads(request.POST.get('data', '1'))
    # paramStrs = buildingParameters(data)


    allData = getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")